import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useRouter } from 'vue-router';

// 用户模块
export const useUserStore = defineStore(
  'user',
  () => {
    const router = useRouter();
    //1.定义描述token
    const userInfo: any = ref({});
    //2.定义修改token的方法, info类型后定
    const setInfo = (info: any) => {
      console.log('info', info);
      userInfo.value = info; // 修复：使用不同的名称避免与参数冲突
    };
    //3.定义移除token的方法
    const removeInfo = () => {
      userInfo.value = {};
    };

    const userObject = ref<{ [key: string]: any }>({
      userId: '', // 加入ws 返回的userid
      camp: '', // 加入房间返回是的阵营
    });

    const setUserObject = (obj: any) => {
      for (const key in obj) {
        userObject.value[key] = obj[key];
      }
    };

    const clearUserObject = () => {
      for (const key in userObject.value) {
        userObject.value[key] = '';
      }
    };

    const delUserObjByField = (field: string) => {
      userInfo.value[field] = '';
    };

    // 重复登录后退出
    const dispose = () => {
      setInfo({});
      clearUserObject();
      router.replace({ name: 'login' });
    };
    return {
      userInfo,
      setInfo,
      removeInfo,
      userObject,
      setUserObject,
      clearUserObject,
      delUserObjByField,
      dispose,
    };
  },
  //pinia数据持久化
  {
    persist: true,
  }
);
